package com.yixq.soa.service.web.auth.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.yixq.soa.service.web.auth.model.TokenModel;
import com.yixq.soa.service.web.auth.service.RedisTokenManager;

public class TokenInterceptor implements HandlerInterceptor {
	@Autowired
	private RedisTokenManager redisTokenManager;
	protected static final Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception exception) throws Exception {
		logger.error(">>>TokenInterceptor>>>>>>>在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）");
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView exception) throws Exception {
		logger.error(">>>TokenInterceptor>>>>>>>请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）");
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		logger.error(">>>TokenInterceptor>>>>>>>在请求处理之前进行调用（Controller方法调用之前）");
		String requestMethod=request.getMethod();
		if(requestMethod.contains("oauth")||requestMethod.contains("apis")){
			return true;
		}
		String appid=request.getHeader("appid");
		String token=request.getHeader("token");
		if(StringUtils.isBlank(appid)||StringUtils.isBlank(token)){
			return true;
		}
		TokenModel tokenModel=new TokenModel(appid, token);
		boolean flag= redisTokenManager.checkToken(tokenModel);
		logger.error(">>>TokenInterceptor>>>>>>>flag>>>>>>>>>"+flag);
		return true;// 只有返回true才会继续向下执行，返回false取消当前请求
		//return flag;
		
	}
}